package main

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"github.com/olahol/melody"
	"net"
	"net/http"
	h "tasty/handler"
	"time"
)

var _r *gin.Engine
var _m *melody.Melody

func init_db(conn string) {
	fmt.Printf("%s : %s", time.Now(), "db init....")
	er := orm.RegisterDataBase("default", "mysql", conn)
	if er != nil {
		panic(er.Error())
	}
	orm.Debug = true

}

func http_service(port string) {
	gin.SetMode(gin.ReleaseMode)
	_r = gin.Default()
	_m = melody.New()
	_r.GET("/plan/list", h.PlanList)
	_r.GET("/plan/new", h.PlanNew)
	_r.GET("/log/query", h.LogQuery)
	_r.GET("/device/register", h.DeviceRegister)
	_r.GET("/device/list", h.DeviceList)

	// websocket
	_r.GET("/", func(c *gin.Context) {
		http.ServeFile(c.Writer, c.Request, "index.html")
	})

	_r.GET("/ws", func(c *gin.Context) {
		_m.HandleRequest(c.Writer, c.Request)
	})

	_m.HandleMessage(func(s *melody.Session, msg []byte) {
		_m.Broadcast(msg)
	})

	_r.GET("/plan/tb", func(c *gin.Context) {
		data := `
	
		`
		c.Data(200, "text/html", []byte(data))
		//c.String(200, string(data))
	})

	_r.Run(port)
}

func socket_service(port string) {

	listener, err := net.Listen("tcp", port)
	if err != nil {
		panic(err.Error())
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}

		go h.ClientHandler(conn)
	}
}

func main() {
	// "root:root@tcp(127.0.0.1:3306)/tasty"
	//db_url := flag.String("db", "db's url", "")
	//flag.Parse()

	db_url := "root:root@tcp(127.0.0.1:3306)/tasty"
	init_db(db_url)
	go http_service(":9090")
	go socket_service(":9999")

	cmd := make(chan string)
	<-cmd
}
